package com.david.webtest.utils

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.text.TextUtils

class PreferenceUtils {

    companion object{
        @SuppressLint("StaticFieldLeak")
        var context:Context? = null;
        @SuppressLint("StaticFieldLeak")
        private lateinit var instance:PreferenceUtils
        var preferences: SharedPreferences? = null
        var editor: SharedPreferences.Editor? = null

        public fun getInstance():PreferenceUtils{
            return instance;
        }

        fun init(context:Application){
            this.context = context
            instance = PreferenceUtils()

            preferences = Companion.context?.getSharedPreferences("web_prefer", Context.MODE_PRIVATE)
            editor = preferences?.edit()
        }
    }

    fun setString(name: String, value:String) {
        editor?.putString(name, value)?.commit()
    }

    fun setBlogName(pageName:String, url:String){
        if (url.contains("?")) {
            val tagPosition = url.indexOf("?")
            setString(url.substring(tagPosition - 5, tagPosition), pageName)
        } else {
            setString(url.substring(url.length - 5), pageName)
        }
    }

    fun getBlogName(url:String):String {
        val result = if (url.contains("?")) {
            val tagPosition = url.indexOf("?")
            getString(url.substring(tagPosition - 5, tagPosition), url)
        } else {
            getString(url.substring(url.length - 5), url)
        }

        return if (TextUtils.isEmpty(result)) url else result
    }

    fun getString(name: String):String {
        return preferences?.getString(name, "") ?: return ""
    }

    fun getString(name: String, value:String):String {
        return preferences?.getString(name, value) ?: return value
    }

    fun setLong(name:String, value:Long){
        editor?.putLong(name, value)?.commit()
    }

    fun getLong(name: String):Long? {
        return preferences?.getLong(name, -1)
    }

    fun getLong(name: String, default:Long):Long {
        return preferences?.getLong(name, default)?:-1
    }

    fun setInt(name:String, value:Int){
        editor?.putInt(name, value)?.commit()
    }

    fun getInt(name: String):Int? {
        return preferences?.getInt(name, -1)
    }

    fun getInt(name: String, default: Int):Int? {
        return preferences?.getInt(name, default)
    }

}
